<template>
  <el-dialog :title="title" v-model="visible" width="400px" append-to-body :before-close="close">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="取消数量" prop="qty">
        <el-input v-model="form.qty" placeholder="请输入取消数量" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          :autosize="{ minRows: 2, maxRows: 4 }"
          type="textarea"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineModel } from "vue";
import { orderCancel } from "@/api/inventory/warehousing";

const { proxy } = getCurrentInstance();
const props = defineProps({
  title: String,
  rowInfo: Object
});
const emits = defineEmits(["success"]);

const visible = defineModel(false);
const form = reactive({
  qty: "",
  remark: ""
});
const validator = (rule, value, cb) => {
  const max = props.rowInfo.qty - props.rowInfo.cancel_qty;
  if (!value) {
    cb(new Error("请输入取消数量"));
  } else if (value > max) {
    cb(new Error(`输入的值不可以大于${max}`));
  } else {
    cb();
  }
};
const rules = {
  qty: [{ required: true, validator: validator, trigger: "blur" }]
};

const close = () => {
  form.qty = "";
  form.remark = "";
  visible.value = false;
};
const confirm = () => {
  proxy.$refs["formRef"].validate(async (valid) => {
    if (!valid) return;
    const res = await orderCancel({
      order_id: props.rowInfo.id,
      order_type: props.rowInfo.type,
      ...form
    });
    if (res && res.code === 0) {
      proxy.$modal.msgSuccess(`${props.title}成功`);
      close();
      emits("success");
      return;
    }
    if (res.code === -1 && res.message) {
      proxy.$modal.msgError(res.message);
    }
  });
};
</script>
